import * as echarts from 'echarts'
import { ref, onMounted, onUnmounted } from 'vue'
import { vegetableinfoGetService } from '../api/admin/vegetableplot'
export function vegetableECharts(targetId, theme = 'back') {
  const chartInstance = ref(null)
  const vagetableview = ref([])
  const third_value = ref([])

  onMounted(async () => {
    const chart = echarts.init(document.getElementById(targetId), theme)
    const res = await vegetableinfoGetService() // 注意这里使用了 async/await
    vagetableview.value = res.data.data

    for (let i = 0; i < vagetableview.value.length; i++) {
      const vegetable = vagetableview.value[i]
      let j = 0

      for (j = 0; j < third_value.value.length; j++) {
        if (vegetable.crops === third_value.value[j].name) {
          if (vegetable.status === '否') {
            third_value.value[j].unfinished++
          } else {
            third_value.value[j].finished++
          }
          break
        }
      }

      if (j === third_value.value.length) {
        const vegetableInfo = {
          name: vegetable.crops,
          unfinished: 0,
          finished: 0
        }
        if (vegetable.status === '否') {
          vegetableInfo.unfinished++
        } else {
          vegetableInfo.finished++
        }

        third_value.value.push(vegetableInfo)
      }
    }
    const names = []
    const unfinishedCounts = []
    const finishedCounts = []
    third_value.value.forEach((item) => {
      names.push(item.name)
      unfinishedCounts.push(item.unfinished)
      finishedCounts.push(item.finished)
    })
    initChart(chart, names, unfinishedCounts, finishedCounts)
    chart.resize()
    chartInstance.value = chart
  })
  onUnmounted(() => {
    if (chartInstance.value) {
      chartInstance.value.dispose()
    }
  })
  return { chartInstance }
}
function initChart(chart, names, unfinishedCounts, finishedCounts) {
  console.log(names)
  chart.setOption({
    title: {
      text: '蔬菜种植状态图',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['已完成', '未完成'],
      right: 20, // 将 legend 稍微向左偏移，离最右边有一定间距
      top: 30 // 设置 legend 距离顶部的距离
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      interval: 1 // 设置 y 轴的步长为 1
    },
    yAxis: {
      type: 'category',
      data: names
    },
    series: [
      {
        name: '已完成',
        type: 'bar',
        stack: '总量',
        label: {
          show: true,
          position: 'insideRight'
        },
        data: finishedCounts // 已完成数量
      },
      {
        name: '未完成',
        type: 'bar',
        stack: '总量',
        label: {
          show: true,
          position: 'insideRight'
        },
        data: unfinishedCounts // 未完成数量
      }
    ]
  })
}
